<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/16
 * Time: 15:38
 */

namespace app\admin\controller;


use app\common\controller\Files;
use app\common\model\CourseBindService;
use app\common\model\teacher\Teacher;
use app\admin\lib\AdminController;
use app\common\model\curriculum\CurriculumClass;
use app\api\model\curriculum\Curriculum as CurriculumModel;
use app\common\model\curriculum\CurriculumPostBill;
use app\common\model\curriculum\CurriculumVideo;
use app\admin\model\ApiResponse;
use app\common\model\Recommend;
use app\common\model\Sales;
use app\common\model\VideoStorage;
use app\common\utils\OssUtil;
use think\Db;
use think\Exception;
use think\Log;

class Curriculum extends AdminController
{

    // 课程分类

    /**
     * 分类列表
     * @return \app\admin\model\PageResponse
     */
    public function class_list() {
        $form = $this->getAndCheckForm([
            ['limit', 'require',],
            ['offset', 'require',],
        ]);
        $result = CurriculumClass::manageList(intval($form['limit']), intval($form['offset']));
        return $result;
    }

    /**
     * 保存课程分类
     * @return ApiResponse
     */
    public function class_save() {
        $form = $this->getAndCheckForm([
            ['class_name', 'require',],
        ]);

        $id = intval($form['class_id'] ?? 0);
        if ($id > 0) {
            $form['class_updatetime'] = time();
            CurriculumClass::update($form,[],CurriculumClass::getSaveFields());
        } else {
            CurriculumClass::create($form, CurriculumClass::getSaveFields());
        }

        return ApiResponse::success();
    }

    /**
     * 删除分类
     * @return ApiResponse
     */
    public function class_del() {
        $form = $this->getAndCheckForm([
            ['class_id', 'require'],
        ]);
        $id = intval($form['class_id']);
        if (CurriculumModel::classUsed($id)) {
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'课程分类使用中，不能删除');
        }
        CurriculumClass::destroy($id);
        return ApiResponse::success();
    }

    /**
     * 获取课程类型名称，包含id和name
     *
     * @return ApiResponse
     */
    public function class_names() {
        return ApiResponse::success(CurriculumClass::classNames());
    }


    // 课程
    /**
     * 课程列表
     * @return \app\admin\model\PageResponse
     */
    public function list() {
        $form = $this->getAndCheckForm([
            ['limit', 'require',],
            ['offset', 'require',],
        ]);
        $result = CurriculumModel::manageList(intval($form['limit']), intval($form['offset']),
            intval($form['class_id']??0), ($form['keywords']??null));
        return $result;
    }



    /**
     * 保存课程
     * @return ApiResponse
     */
    public function save() {
        $form = $this->getAndCheckForm([
            ['curriculum_id', 'integer',],
            ['curriculum_class', 'require',],
            ['curriculum_name', 'require',],
            ['curriculum_description', 'require',],
            ['curriculum_pic', 'require',],
            ['curriculum_sales', 'integer',],
            ['curriculum_sale_price', 'require|float',],

            ['bind_column_id', 'integer',],
        ]);
        // 自动下载内容中的远程图片并同步到oss
        if (isset($form['curriculum_description'])) $form['curriculum_description'] = Files::imgSync($form['curriculum_description']);
        $price = $form['curriculum_sale_price'];
        if (!empty($form['curriculum_sales'])) {
            $sales = Sales::get($form['curriculum_sales']);
            if ($sales) {
                $re = $sales->finalPrice($form['curriculum_sale_price']);
                $price = $re['price'];
            }
        }
        if ($price < 0) {
            ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'价格不正确，请检查价格和优惠活动');
        }

        try{

            if (isset($form['curriculum_id'])) {
                $form['curriculum_updatetime'] = time();
                $model = CurriculumModel::update($form, [], CurriculumModel::getSaveFields());
            } else {
                $form['curriculum_addtime'] = time();
                $model = CurriculumModel::create($form, CurriculumModel::getSaveFields());
            }

            if ($form['service_enable']) {
                $params = [
                    'curriculum_id' => intval($model->curriculum_id),
                    'bind_column_id' => $form['bind_column_id'] ? intval($form['bind_column_id']) : null,
                    'online_course' => ('true'==$form['online_course']) ? 1 : 0 ,
                    'fupan_answer' => ('true'==$form['fupan_answer']) ? 1 : 0 ,
                    'exclusive_group' => ('true'==$form['exclusive_group']) ? 1 : 0 ,
                    'stock_analysis_report' => ('true'==$form['stock_analysis_report']) ? 1 : 0 ,
                    'expired' => intval($form['expired']) ,
                    'article_reference' => ('true'==$form['article_reference']) ? 1 : 0 ,
                    'article_report' => ('true'==$form['article_report']) ? 1 : 0 ,
                ];
                CourseBindService::insertOrUpdate($params);
            }


            return ApiResponse::success();
        }catch (\Exception $e){
            Log::error($e->getMessage());
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED, $e->getMessage());
        }
    }

    /**
     * 删除课程
     * @return ApiResponse
     */
    public function del() {
        $form = $this->getAndCheckForm([
            ['curriculum_id', 'require'],
        ]);
        $id = $form['curriculum_id'];
        CurriculumModel::destroy($id);
        return ApiResponse::success();
    }

    /**
     * 设置课程隐藏或取消
     * @return ApiResponse
     */
    public function set_hide() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
            ['hide', 'require',],
        ]);

        $id = intval($form['id']);
        $hide = intval($form['hide']);

        if (!$hide && !CurriculumModel::checkPreviewVideo($id)) {
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'必须设置一个试看视频');
        }

        try{
            CurriculumModel::setHide($id, $hide);

            return ApiResponse::success($form);
        }catch (Exception $ex){
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED, $ex->getMessage());
        }
    }

    public function curriculum_names() {
        $list = CurriculumModel::names();
        return ApiResponse::success($list);
    }

    /**
     * 推荐课程
     * @return ApiResponse
     */
    public function recommend() {

        $form = $this->getAndCheckForm([
            ['rec_item_type', '^[1-2]$',],
            ['rec_item_id', 'integer',],
            ['rec_id', 'integer',],
            ['cancel', 'integer',],
        ]);

        $cancel = !empty($form['cancel']);
        if ($cancel && isset($form['rec_id']))  {
            Recommend::destroy($form['rec_id']);
        } elseif (isset($form['rec_item_type']) && isset($form['rec_item_id'])) {
            if (1 == $form['rec_item_type']) {
                $v = CurriculumVideo::get($form['rec_item_id']);
                if (empty($v)) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'视频id不存在');
            } else {
                $c = CurriculumModel::get($form['rec_item_id']);
                if (empty($c)) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'课程id不存在');
            }
            Recommend::create([
                'rec_item_type' => $form['rec_item_type'],
                'rec_item_id' => $form['rec_item_id'],
                'rec_time' => time(),
            ]);
        } else {
            ApiResponse::error(ApiResponse::ERR_FORM_INVALID,'缺少参数');
        }

        return ApiResponse::success();
    }



    // 课程视频

    /**
     * 课程视频列表
     * @return \app\admin\model\PageResponse
     */
    public function video_list() {
        $form = $this->getAndCheckForm([
            ['limit', 'require',],
            ['offset', 'require',],
        ]);

        $hide = intval($form['hide']??-1);
        $result = CurriculumVideo::manageList(
            intval($form['limit']),
            intval($form['offset']),
            intval($form['curriculum_id']??0),
            (0 == $hide ? 0 : (1 == $hide ? 1 : null))
        );

        return $result;
    }

    /**
     * 保存课程视频，插入和修改
     * @return ApiResponse
     */
    public function video_save() {
        $form = $this->getAndCheckForm([
            ['video_curriculum', 'require',],
            ['video_teacher', 'require|integer',],
            ['video_title', 'require',],
        ]);

        if (isset($form['video_free_start_time'])) $form['video_free_start_time'] = strtotime($form['video_free_start_time']);
        if (isset($form['video_free_end_time'])) $form['video_free_end_time'] = strtotime($form['video_free_end_time']);
        $id = intval($form['video_id'] ?? 0);
        $video = CurriculumVideo::get($id);
        unset($form['rec_id']);
        // 自动下载内容中的远程图片并同步到oss
        if (isset($form['curriculum_description'])) $form['curriculum_description'] = Files::imgSync($form['curriculum_description']);
        if ($video) {
            $form['video_updatetime'] = time();
            if ($form['video_url'] != $video->video_url) OssUtil::delete($video->video_url);
            if ($form['video_cover'] != $video->video_cover) OssUtil::delete($video->video_cover);

            CurriculumVideo::update($form, [], CurriculumVideo::getSaveFields());
        } else {
            $form['video_addtime'] = time();
            Db::transaction(function () use ($form, $video) {
                $vs = VideoStorage::create(['name' => '']); // 创建视频上传记录，用于网易点播上传
                $form['vid'] = $vs->id;
                $video = CurriculumVideo::create($form, CurriculumVideo::getSaveFields());
                CurriculumModel::countVideos(intval($video->video_curriculum));
                Teacher::countNumVideo($video->video_teacher);
            });
        }

        return ApiResponse::success();
    }

    /**
     * 删除视频
     * @return ApiResponse
     */
    public function video_del() {
        $form = $this->getAndCheckForm([
            ['video_id', 'require|integer',],
        ]);
        $id = intval($form['video_id']);
        if ($id > 0) {
            $video = CurriculumVideo::get($id);
            OssUtil::delete($video->video_url);
            OssUtil::delete($video->video_cover);
            CurriculumVideo::destroy($id);
            CurriculumModel::countVideos(intval($video->video_curriculum));
            Teacher::countNumVideo($video->video_teacher);
        }
        return ApiResponse::success();
    }

    /**
     * 设置课程隐藏或取消
     * @return ApiResponse
     */
    public function video_set_hide() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
            ['hide', 'require|integer',],
        ]);

        $video = CurriculumVideo::get($form['id']);
        if ($video) $video->setHide(intval($form['hide']));

        return ApiResponse::success();
    }

    /**
     * 批量修改排序
     * @return ApiResponse
     */
    public function video_set_sorts() {
        $sorts = input('post.sorts');
        $sorts = json_decode($sorts, true);
        $list = [];
        foreach ($sorts as & $sort) {
            $list[] = [
                'video_id' => intval($sort['id']),
                'video_sort' => intval($sort['sort']),
            ];
        }
        if (count($list) > 0) {
            $cv = new CurriculumVideo();
            $cv->saveAll($list);
        }

        return ApiResponse::success();
    }

    // 晒单

    public function bill_list() {
        $form = $this->getAndCheckForm([
            ['video_id', 'require|integer',],
        ]);

        $page = CurriculumPostBill::manageList(
            intval($form['limit']), intval($form['offset']), intval($form['video_id']));

        return $page;
    }

    public function bill_save() {
        $form = $this->getAndCheckForm([
            ['bill_video', 'require|integer',],
            ['bill_trading_day', 'require',],
            ['bill_income', 'require',],
            ['bill_stock_code', 'require',],
            ['bill_stock_name', 'require',],
        ]);

        $video = CurriculumVideo::get($form['bill_video']);
        if (empty($video)) ApiResponse::success(ApiResponse::ERR_FORM_INVALID);

        $form['bill_curriculum'] = $video->video_curriculum;
        if (isset($form['bill_id']) && $form['bill_id'] > 0) {
            CurriculumPostBill::update($form);
        } else {
            CurriculumPostBill::create($form);
        }

        return ApiResponse::success();
    }

    public function bill_del() {
        $form = $this->getAndCheckForm([
            ['bill_id', 'require|integer',],
        ]);

        if ($form['bill_id'] > 0) {
            CurriculumPostBill::destroy($form['bill_id']);
        }

        return ApiResponse::success();
    }

}